import React from 'react';
import { ItemInfoProps } from '@/pages/market/Item';
import { useModel } from '@@/plugin-model/useModel';
import { Button, Space } from 'antd';
import { ModalForm, ProFormDigit, ProFormText } from '@ant-design/pro-form';
import { isAddress } from 'ethers/lib/utils';
import styles from '@/pages/market/Item/index.less';
import ProCard from '@ant-design/pro-card';

const SaleFormCard: React.FC = () => {
  // 全局变量
  const { initialState } = useModel('@@initialState');

  if(!initialState){
    return <div/>
  }
  // 页面变量
  const {item,owner,approved,tokenId,loading} = useModel('item');
  const { currentAccount,provider,contracts:{saleContract} } = initialState;

  if(!item){
    return <div/>
  }

  if(currentAccount?.address!==owner){
    return <div/>
  }

  if(owner==saleContract.address){
    return <div/>
  }

  if(approved!==saleContract.address){
    return <div/>
  }

  return(
    <ProCard className={styles.itemCard} headerBordered bordered title="操作" loading={loading}>
      <ModalForm<{
        price: number;
        buyer: string;
      }>
        title="设置价格"
        trigger={<Button type="primary">定价出售</Button>}
        onFinish={async (values) => {
          if (!values.buyer || values.buyer === '') {
            values.buyer = '0x0000000000000000000000000000000000000000';
          }
          try {
            const signer = await provider.getSigner();
            const overrides = {
              from: await signer.getAddress(),
              gasPrice: await provider.getGasPrice(),
              gasLimit: 500000,
              nonce: await signer.getTransactionCount(),
            };
            await saleContract.callStatic.create(
              tokenId,
              values.price,
              values.buyer,
              overrides,
            );
            const tx = await saleContract
              .connect(signer)
              .create(
                tokenId,
                values.price,
                values.buyer,
                overrides,
              );
            await tx.wait();
            window.location.reload();
          } catch (e) {
            console.error(e);
          }
          return true;
        }}
      >
        <ProFormDigit
          name="price"
          label="定价"
          placeholder="金额"
          rules={[
            {
              required: true,
              message: '请输入定价',
            },
          ]}
          fieldProps={{}}
        />
        <ProFormText
          name="buyer"
          label={'指定用户'}
          placeholder={'用户账户'}
          rules={[
            {
              validator: (_, value) =>
                isAddress(value) || !value
                  ? Promise.resolve()
                  : Promise.reject(new Error('地址格式错误')),
            },
          ]}
        />
      </ModalForm>
    </ProCard>
  )
};

export default SaleFormCard;
